const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const success = require('../../utils/responses').success;
const failure = require('../../utils/responses').failure;
const NotFoundError = require('../../utils/errors').NotFoundError;

const moment = require('moment');
moment.locale('zh-cn'); // 如果需要设置中文本地化等相关配置可以加上这行

// 连接 MongoDB 数据库，替换为你自己的真实连接字符串
mongoose.connect('mongodb://localhost:27017/control-book', {
    useNewUrlParser: true,
    useUnifiedTopology: true
});

const Book = require('../../models/book');
const Like = require('../../models/like');
const User = require('../../models/user');

// 点赞、取消赞
router.post('/', async function (req, res) {
  try {
      const userId = req.user.id;
      const { bookId } = req.body;
      console.log(userId)

      const book = await Book.findById(bookId);
      if (!book) {
          throw new NotFoundError('书籍不存在');
      }

      const like = await Like.findOne({ bookId, userId });
      console.log(like);

      // 如果没有点赞过，那就新增。并且书籍的 likesCount + 1
      if (!like) {
          const newLike = new Like({ bookId, userId, 
            createdAt: moment().format('YYYY-MM-DD HH:mm:ss'), 
            updatedAt: moment().format('YYYY-MM-DD HH:mm:ss') });
          await newLike.save();
          book.likesCount += 1;
          await book.save();
          success(res, '点赞成功。');
      } else {
          // 如果点赞过了，那就删除。并且书籍的 likesCount - 1
          await like.deleteOne();
          book.likesCount -= 1;
          await book.save();
          success(res, '取消赞成功。');
      }

  } catch (error) {
    console.log(error);
      failure(res, error);
  }
});

// 查询用户点赞的书籍
router.get('/', async function (req, res) {
  try {
    const query = req.query;
    const currentPage = Math.abs(Number(query.currentPage)) || 1;
    const pageSize = Math.abs(Number(query.pageSize)) || 10;
    const offset = (currentPage - 1) * pageSize;

    // 查询当前用户（这里只是简单校验下用户是否存在，可根据实际情况完善错误处理逻辑）
    const user = await User.findById(query.userId);
    if (!user) {
      throw new NotFoundError('用户不存在');
    }

    // 先在Like表中根据userId查找对应的bookId列表
    const likedBookIds = await Like.find({
      userId: query.userId
    })
   .select('bookId')
   .exec();

    const bookIds = likedBookIds.map(like => like.bookId);

    // 再根据获取到的bookId列表在Book表中查询对应的书籍
    const books = await Book.find({
      _id: {
        $in: bookIds
      }
    })
   .select('-CategoryId -UserId') // 排除指定字段
   .sort({ id: -1 })
   .limit(pageSize)
   .skip(offset);

    // 查询当前用户点赞过的书籍总数
    const count = await Book.countDocuments({
      _id: {
        $in: bookIds
      }
    });

    success(res, '查询用户点赞的书籍成功。', {
      books,
      pagination: {
        total: count,
        currentPage,
        pageSize
      }
    });
  } catch (error) {
    failure(res, error);
  }
});

router.get('/:_id', async function (req, res) {
  try {
    const book = await Book.findById(req.params._id);
    const currentPage = Math.abs(Number(req.query.currentPage)) || 1;
    const pageSize = Math.abs(Number(req.query.pageSize)) || 10;
    const offset = (currentPage - 1) * pageSize;

    if (!book) {
      throw new NotFoundError('书籍不存在');
    }

    // 先在Like表中根据userId查找对应的bookId列表
    const likedBookIds = await Like.find({
      bookId: req.params._id
    })
   .select('userId')
   .exec();
   console.log(likedBookIds);

    const userIds = likedBookIds.map(like => like.userId);
    console.log(userIds);

    // 再根据获取到的bookId列表在Book表中查询对应的书籍
    const books = await User.find({
      _id: {
        $in: userIds
      }
    })
   .select('-CategoryId -UserId') // 排除指定字段
   .sort({ id: -1 })
   .limit(pageSize)
   .skip(offset);

    // 查询当前用户点赞过的书籍总数
    const count = await User.countDocuments({
      _id: {
        $in: userIds
      }
    });

    success(res, '查询用户点赞的书籍成功。', {
      books,
      pagination: {
        total: count,
        currentPage,
        pageSize
      }
    });
  } catch (error) {
    console.log(error);
    failure(res, error);
  }
});

module.exports = router;